package user.zc.action;

import user.zc.action.comp.SaveOrUpdateAction;
import user.zc.controller.IConnect;
import user.zc.vo.ConnectionDTO;

import javax.swing.*;
import java.util.Map;
import java.util.function.Consumer;

public class AddOrUpdateConnectionAction extends SaveOrUpdateAction<ConnectionDTO,Boolean> {

    public AddOrUpdateConnectionAction(IConnect connectCollector, Consumer<Boolean> callback){
        this(connectCollector,null,null,callback);
    }

    public AddOrUpdateConnectionAction(IConnect connectCollector, String name, ConnectionDTO connectionDTO, Consumer<Boolean> callback){
        super(callback,connectionDTO,500,4*SCALE);
        try {
            addItem("名称","name",true,name);
            addItem("地址","url",true);
            addItem("用户","user",true);
            addItem("密码","password",true);
            openDialog(name!=null?"修改连接【"+name+"】":"新增连接",(dto)->{
                try {
                    connectCollector.saveOrUpdate(mapping().get("name"),dto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                JOptionPane.showMessageDialog(null,"保存成功");
                call(true);
            });
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null,
                    e.getMessage(), "错误提示", JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    protected ConnectionDTO map2Entity(Map<String, String> map) {
        return new ConnectionDTO(map.get("url"),map.get("user"),map.get("password"));
    }
}
